﻿using Application.User;
using AutoMapper;
using Common;
using Common.Page;
using Domain.Repositories;
using Grpc;
using Grpc.Net.Client;
using Infrastructure;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Timeouts;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using WebApi.Controllers.Models.User;

namespace WebApi.Controllers
{
    /// <summary>
    /// 用户
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class UserController : ControllerBase
    {
        private readonly IUserRepository _userRepository;
        private readonly IMapper _mapper;
        private readonly IMediator _mediator;

        /// <summary>
        /// 用户
        /// </summary>
        /// <param name="userRepository"></param>
        /// <param name="mapper"></param>
        /// <param name="mediator"></param>
        public UserController(IUserRepository userRepository, IMapper mapper, IMediator mediator)
        {
            _userRepository = userRepository;
            _mapper = mapper;
            _mediator = mediator;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginUser"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        [AllowAnonymous]
        public Task<Result<UserToken>> Login(LoginCommand loginUser) => _mediator.Send(loginUser);


        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetUserList")]
        public async Task<PageList<UserVo>> GetUserList(QueryUserPageModel query)
        {
            var users = await _userRepository.GetPageListAsync(u => u.Id >= query.IdGreaterEqual && u.Id < query.IdLess,u=>u.Id, query.PageIndex, query.PageSize);

            return new PageList<UserVo>
            {
                Data = _mapper.Map<List<UserVo>>(users.Data),
                PageInfo = new PageInfo
                {
                    PageSize = query.PageSize,
                    PageIndex = query.PageIndex,
                    TotalCount = users.PageInfo.TotalCount
                }
            };
        }

        /// <summary>
        /// 用户详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        //[EnableRateLimiting("FixedWindow")]
        [RequestTimeout("TimeOutPolicy")]
        public async Task<UserVo> GetUser(long id)
        {
            await Task.Delay(TimeSpan.FromSeconds(10));
            
            var user = await _userRepository.GetAsync(u=>u.Id==id);

            return _mapper.Map<UserVo>(user);
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Result<long>> AddUser(CreateUserCommand user)
        {
            var userId = await _mediator.Send(user);
            
            return userId == 0 ? ResultBuilder.Fail(0L,"用户已存在") : ResultBuilder.Success(userId);
        }
        
        /// <summary>
        /// grpc服务测试
        /// </summary>
        /// <returns></returns>
        [HttpGet("GrpcServiceTest")]
        [AllowAnonymous]
        public IActionResult GrpcServiceTest(long userId)
        {
            using var channel = GrpcChannel.ForAddress("http://localhost:5269");
            var client = new UserService.UserServiceClient(channel);
            var result =  client.GetUserInfo(new GetUserInfoRequest()
            {
                Id = userId
            });
            return new JsonResult(result);
        }
    }
}